//
//  FeedbackViewController.m
//  FeedbackPhone
//
//  Created by David Aspinall on 06/04/09.
//  Copyright Plan-B Software 2009. All rights reserved.
//

#import "FeedbackViewController.h"
#import <AddressBook/AddressBook.h>
#import "NSURLRequest+Additions.h"

NSString *JRFeedbackType[JRFeedbackController_SectionCount] = {
	@"BUG", // JRFeedbackController_BugReport
	@"FEATURE", // JRFeedbackController_FeatureRequest
	@"SUPPORT" // JRFeedbackController_SupportRequest
};


@implementation FeedbackViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor];   
	
	NSString *title = [NSString stringWithFormat:@"%@ Feedback", [[NSProcessInfo processInfo] processName]];
	[textView setText:title];
	
	emailList = [[NSMutableArray alloc] init];
	
	ABAddressBookRef addressBook = ABAddressBookCreate();
	NSArray *people = (NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
	NSLog( @"Peope %@", people );
	for (id peopleRecord in people)
	{
		ABRecordRef aRecord = (ABRecordRef)peopleRecord;
		
		CFStringRef firstName = ABRecordCopyValue(aRecord, kABPersonFirstNameProperty);
		CFStringRef lastName  = ABRecordCopyValue(aRecord, kABPersonLastNameProperty);
		
		ABMutableMultiValueRef multi = ABRecordCopyValue(aRecord, kABPersonEmailProperty);
		for (CFIndex i = 0; i < ABMultiValueGetCount(multi); i++)
		{
//			CFStringRef cruftylabel = ABMultiValueCopyLabelAtIndex(multi, i);
			CFStringRef email = ABMultiValueCopyValueAtIndex(multi, i);
						
//			NSString *fullname = [NSString stringWithFormat:@"%@ %@ (%@)", firstName, lastName, label];
//			NSLog( @"%@ = %@", fullname, email );
			[emailList addObject:(NSString *)email];			
//			CFRelease(cruftlabel);
			CFRelease(email);
		}
	}
	[people release];
	CFRelease(addressBook);
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	return [emailList count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	return [emailList objectAtIndex:row];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc 
{
	[emailList release];
    [super dealloc];
}

- (IBAction)switchSectionAction:(UISegmentedControl*)sender 
{
	currentSection = [sender selectedSegmentIndex];
	
	NSString *title = [NSString stringWithFormat:@"%@ %@", [[NSProcessInfo processInfo] processName], JRFeedbackType[currentSection]];
	[textView setText:title];
}

- (IBAction)submitAction:(id)sender 
{
	NSLog( @"Submit Action" );
    [textView setEditable:NO];
	[self postFeedback];
}

- (void)postFeedback 
{
    NSString *postURL = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"DAFeedbackURL"];
    if ([[NSUserDefaults standardUserDefaults] stringForKey:@"DAFeedbackURL"]) 
	{
        postURL = [[NSUserDefaults standardUserDefaults] stringForKey:@"DAFeedbackURL"];
    }

    NSString *email = @"<email suppressed>";
	int row = [emailAddressComboBox selectedRowInComponent:0];
	if ( row < [emailList count] )
	{
		email = [emailList objectAtIndex:row];
	}
	
    NSDictionary *form = [NSDictionary dictionaryWithObjectsAndKeys:
                          JRFeedbackType[currentSection], @"feedbackType",
                          [textView text], @"feedback",
                          email, @"email",
                          [[NSProcessInfo processInfo] processName], @"appName",
                          [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"], @"bundleID",
                          [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"], @"version",
                          nil];
	
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:postURL] postForm:form];
    [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)closeFeedback 
{
    NSLog(@"-[DAFeedback close] %@", [self parentViewController]);
//	[self cl
//        [[gFeedbackController window] orderOut:self];
//        [gFeedbackController release];
//        gFeedbackController = nil;
//    }
}

- (void)connectionDidFinishLoading:(NSURLConnection*)connection 
{
    // TODO Drop Thank you sheet
    NSLog(@"-[DAFeedback connectionDidFinishLoading:%@]", connection);
    [self closeFeedback];
}

- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error 
{
    NSLog(@"-[DAFeedback connection:didFailWithError:%@]", error);
    [self closeFeedback];
}


@end
